package xin.marcher.module.replenished.repository;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.replenished.domain.entity.LeadAllocDO;
import xin.marcher.module.replenished.exception.ReplenishedCodeEnum;
import xin.marcher.module.replenished.mapper.LeafAllocNoMapper;

import javax.annotation.Resource;
import java.util.Date;

/**
 * redis 和数据库交互相关的 资源类
 *
 * 
 */
@Repository
public class LeafAllocNoRepository {

    @Resource
    private LeafAllocNoMapper leadAllocNoMapper;

    /**
     * 默认更新号段
     *
     * @param bizTag
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public LeadAllocDO updateMaxIdAndGet(String bizTag) {
        int ret = leadAllocNoMapper.updateMaxId(bizTag);
        if (ret != 1) {
            throw new BaseBizException(ReplenishedCodeEnum.REPLENISHED_NO_GEN_ERROR);
        }
        return leadAllocNoMapper.findByBizTag(bizTag);
    }

    /**
     * 指定更新号段
     *
     * @param bizTag
     * @param nextStep
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public LeadAllocDO updateMaxIdByDynamicStepAndGet(String bizTag, int nextStep) {
        int ret = leadAllocNoMapper.updateMaxIdByDynamicStep(bizTag, nextStep);
        if (ret != 1) {
            throw new BaseBizException(ReplenishedCodeEnum.REPLENISHED_NO_GEN_ERROR);
        }
        return leadAllocNoMapper.findByBizTag(bizTag);
    }

    /**
     * 初始化一个缓存key对象
     *
     * @param bizTag
     */
    public void insertLeadAlloc(String bizTag) {
        LeadAllocDO leadAllocDO = new LeadAllocDO();
        leadAllocDO.setStep(500);
        leadAllocDO.setBizTag(bizTag);
        leadAllocDO.setUpdateTime(new Date());
        leadAllocNoMapper.insert(leadAllocDO);
    }
}
